package com.ruoyi.order.service.impl;

import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.order.mapper.WorkOrderMapper;
import com.ruoyi.order.domain.WorkOrder;
import com.ruoyi.order.service.IWorkOrderService;

/**
 * 工单管理Service业务层处理
 * 
 * @author admin
 * @date 2023-06-02
 */
@Service
public class WorkOrderServiceImpl implements IWorkOrderService 
{
    private static final int REPLIED = 1;
    @Autowired
    private WorkOrderMapper workOrderMapper;

    /**
     * 查询工单管理
     * 
     * @param code 工单管理主键
     * @return 工单管理
     */
    @Override
    public WorkOrder selectWorkOrderByCode(Long code)
    {
        return workOrderMapper.selectWorkOrderByCode(code);
    }

    /**
     * 查询工单管理列表
     * 
     * @param workOrder 工单管理
     * @return 工单管理
     */
    @Override
    public List<WorkOrder> selectWorkOrderList(WorkOrder workOrder)
    {
        return workOrderMapper.selectWorkOrderList(workOrder);
    }

    /**
     * 新增工单管理
     * 
     * @param workOrder 工单管理
     * @return 结果
     */
    @Override
    public int insertWorkOrder(WorkOrder workOrder)
    {

        //添加创建人
        workOrder.setCreatedUser("admin");
        //添加是否回复 0，未回复
        workOrder.setReply(0l);
        //添加创建时间
        workOrder.setCreatedTime(new Date());
        return workOrderMapper.insertWorkOrder(workOrder);
    }

    /**
     * 修改工单管理
     * 
     * @param workOrder 工单管理
     * @return 结果
     */
    @Override
    public int updateWorkOrder(WorkOrder workOrder)
    {
        if (workOrder.getUser()!=null) {
            workOrder.setDispatch(1L);
        }
        //添加修改时间
        workOrder.setUpdateUser("admin");
        workOrder.setUpdateTime(new Date());
        return workOrderMapper.updateWorkOrder(workOrder);
    }

    /**
     * 批量删除工单管理
     * 
     * @param codes 需要删除的工单管理主键
     * @return 结果
     */
    @Override
    public int deleteWorkOrderByCodes(Long[] codes)
    {
        //遍历工单编号，获取工单信息，判断是否回复，回复不可以删除
        for (Long code : codes) {
            WorkOrder workOrder = workOrderMapper.selectWorkOrderByCode(code);
            System.out.println(workOrder.getReply());
            if (workOrder.getReply() == REPLIED) {
                throw new RuntimeException("已回复，不允许删除");
            }
        }
        return workOrderMapper.deleteWorkOrderByCodes(codes);
    }

    /**
     * 删除工单管理信息
     * 
     * @param code 工单管理主键
     * @return 结果
     */
    @Override
    public int deleteWorkOrderByCode(Long code)
    {
        //获取工单信息，判断是否回复，回复不可以删除
        WorkOrder workOrder = workOrderMapper.selectWorkOrderByCode(code);
        if (workOrder.getReply()== REPLIED){
            throw new RuntimeException("已回复，不允许删除");
        }
        return workOrderMapper.deleteWorkOrderByCode(code);
    }
}
